package com.heima.article.service.impl;
// 爱情不是随便许诺,算了,不想再说了

import com.alibaba.fastjson.JSONArray;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ApAuthorService;
import com.heima.article.service.FreeMarkerService;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.file.service.MinioService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.postgresql.shaded.com.ongres.scram.common.util.StringWritable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class FreeMarkerServiceImpl implements FreeMarkerService {


    @Autowired
    private Configuration configuration;

    @Autowired
    private ApArticleService apArticleService;

    @Autowired
    private MinioService minioService;
    /**
     * 生成文章静态信息
     *
     * @param apArticle
     * @param content
     */
    @Async
    public void buildContentHtml(ApArticle apArticle, String content) {
        try {
            // 读取模板页面
            Template template = configuration.getTemplate("artcle.ftl");
            // 准备数据模型
            Map map = new HashMap<>();
            map.put("content", JSONArray.parseArray(content));
            // 调用API生成静态页面,存入流中
            StringWriter stringWriter = new StringWriter();
            template.process(map,stringWriter);
            // 放入minio
            String fileName = apArticle.getId() + ".html";
            // 不用关
            InputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
            // 获取到访问路径

            String url = minioService.uploadHtmlFile("",fileName,inputStream);
            log.info("url ========={}",url);
            // 写入数据库的static_url字段中
            ApArticle apArticle1 = new ApArticle();
            apArticle1.setId(apArticle.getId());
            apArticle1.setStaticUrl(url);
            apArticleService.updateById(apArticle1);
        } catch (Exception e) {
            e.printStackTrace();
            throw  new LeadException(AppHttpCodeEnum.UPLOAD_ERROR);
        }

    }
}
